<template>
  <div style="background-color: #fff">
    <!--表单  -->
    <van-cell-group label-align="right">
      <van-field
        placeholder="请输入产品主标题"
        v-model="shopname"
        required
        maxlength="17"
      >
        <span slot="label">产品主标题：</span>
      </van-field>
      <van-field
        placeholder="产品优势、卖点等"
        v-model="subtitle"
        rows="2"
        autosize
        type="textarea"
        maxlength="27"
        show-word-limit
      >
        <span slot="label">产品副标题：</span>
      </van-field>
      <van-field
        placeholder="请输入产品定金"
        v-model="shopent"
        required
        type="number"
      >
        <span slot="label"> 产品定金：</span>
      </van-field>

      <div
        style="
          border-bottom: 1px solid #ebedf0;

          margin: 0 15px;
        "
      >
        <span
          style="
            width: auto;
            line-height: 300%;
            margin-right: 12px;
            color: #646566;
          "
          >产品规格:</span
        >
        <div style="display: flex; border-top: 1px solid #ebedf0">
          <span
            slot="label"
            style="border-right: 1px solid #eeeeee; width: 60%"
          >
            <van-field placeholder="产品规格名称" v-model="parameterone">
            </van-field
          ></span>

          <span slot="label" style="width: 38%">
            <van-field placeholder="金额" v-model="parameone" type="number">
            </van-field>
          </span>
          <span style="line-height: 300%">（元）</span>
        </div>
        <div style="display: flex; border-top: 1px solid #ebedf0">
          <span
            slot="label"
            style="border-right: 1px solid #eeeeee; width: 60%"
          >
            <van-field placeholder="产品规格名称" v-model="parametertwo">
            </van-field
          ></span>

          <span slot="label" style="width: 38%">
            <van-field placeholder="金额" v-model="parametwo" type="number">
            </van-field>
          </span>
          <span style="line-height: 300%">（元）</span>
        </div>
        <div style="display: flex; border-top: 1px solid #ebedf0">
          <span
            slot="label"
            style="border-right: 1px solid #eeeeee; width: 60%"
          >
            <van-field placeholder="产品规格名称" v-model="parameterthre">
            </van-field
          ></span>

          <span slot="label" style="width: 38%">
            <van-field placeholder="金额" v-model="paramethre" type="number">
            </van-field>
          </span>
          <span style="line-height: 300%">（元）</span>
        </div>
        <div style="display: flex; border-top: 1px solid #ebedf0">
          <span
            slot="label"
            style="border-right: 1px solid #eeeeee; width: 60%"
          >
            <van-field placeholder="产品规格名称" v-model="parameterfour">
            </van-field
          ></span>

          <span slot="label" style="width: 38%">
            <van-field placeholder="金额" v-model="paramefour" type="number">
            </van-field>
          </span>
          <span style="line-height: 300%">（元）</span>
        </div>
      </div>

      <van-field
        placeholder="请输入产品全款"
        v-model="shophone"
        required
        type="number"
      >
        <span slot="label">产品全款：</span>
      </van-field>
      <van-field
        placeholder="请输入产品库存"
        v-model="stock"
        type="number"
        required
      >
        <span slot="label">产品库存：</span>
      </van-field>

      <!-- 上传 -->
      <div>
        <van-field readonly required :border="false">
          <span slot="label">上传产品主图</span>
        </van-field>
        <div
          style="
            display: flex;
            width: 80px;
            position: relative;
            margin-left: 10px;
          "
        >
          <i
            v-if="editid != 0"
            v-show="drwpan"
            style="position: absolute; z-index: 112; right: 0; padding: 5px"
            @click="drw()"
            >X</i
          >
          <img
            v-if="editid != 0"
            v-show="drwpan"
            :src="drawing"
            alt=""
            width="80px"
            height="80px"
            style="position: absolute; z-index: 111"
          />
          <van-uploader
            :max-count="1"
            v-model="filest"
            upload-text="上传产品主图"
            style=""
            v-show="show_upload"
            :before-read="beforeR"
            :after-read="afterR"
            :before-delete="beforeD"
          />
        </div>
      </div>
      <van-field class="work_type">
        <span slot="label">产品施工类型:</span>
        <v-select
          slot="input"
          style="width: 200px"
          :multiple="true"
          :selectable="selectWkType"
          :searchable="false"
          :close-on-select="false"
          :options-label="'label'"
          :options-value="'value'"
          v-model="wkTypeSelected"
          :options="types"
          placeholder="可多选三种"
        ></v-select>
      </van-field>
      <van-field placeholder="请输入产品类别" v-model="custom">
        <span slot="label">其他施工类型：</span>
      </van-field>
      <div>
        <van-field readonly :border="false">
          <span slot="label">产品详细图（非必填）</span>
        </van-field>
        <div style="width: 80px; margin-left: 10px; position: relative">
          <i
            v-if="editid != 0"
            v-show="figua"
            style="position: absolute; z-index: 112; right: 0; padding: 5px"
            @click="figu()"
            >X</i
          >
          <img
            v-if="editid != 0"
            v-show="figua"
            :src="figures"
            alt=""
            width="80px"
            height="80px"
            style="position: absolute; z-index: 111"
          />
          <van-uploader
            :max-count="1"
            v-model="fileList"
            upload-text="产品详细图"
            style=""
            v-show="show_upload"
            :before-read="beforeRead"
            :after-read="afterRead"
            :before-delete="beforeDelete"
          />
        </div>
      </div>

      <van-field
        placeholder="流量大小、功率大小、动力大小、等其他参数"
        v-model="shoptext"
        rows="2"
        autosize
        type="textarea"
        maxlength="50"
        show-word-limit
        required
      >
        <span slot="label">产品参数：</span>
      </van-field>
      <!-- 弹窗 -->
      <van-popup v-model="showcity" position="bottom">
        <van-tree-select
          :items="items"
          :active-id.sync="activeId"
          @click-item="itemck"
          :main-active-index.sync="activeIndex"
        />
      </van-popup>
    </van-cell-group>

    <div style="padding: 0 16px; margin-top: 15px">
      <van-button
        style="
          width: 100%;
          font-size: 18px;
          color: white;
          background: rgb(255, 170, 37);
        "
        @click="upcard()"
        >请提交信息，等待审核</van-button
      >
    </div>
  </div>
</template>

<script>
import {
  Uploader,
  Toast,
  Button,
  Checkbox,
  Field,
  Popup,
  Area,
  TreeSelect,
} from 'vant';
import lrz from 'lrz';
import { getLocalStorage } from '@/utils/local-storage';
import {
  storageUpload,
  authInfo,
  qustores,
  adduct,
  classifica,
  goodsDetail,
  addlianmen,
  upshod,
  upsholiand,
} from '@/api/api';
import areaList from '@/views/user/module-address-edit/area_all.json';
export default {
  name: 'adduct',
  data() {
    return {
      userId: Number(getLocalStorage('userId').userId),
      fileList: [],
      areaList: areaList,
      //   fileL: [],
      drawing: '',
      filest: [],
      custom: '',
      figures: '',
      figua: true,
      parametercc: '',
      drwpan: true,
      wkTypeSelected: [],
      wkType: [],
      images: [],
      types: [],
      show_upload: true,
      showstype: false,
      parameterone: '',
      parametertwo: '',
      parameterthre: '',
      parameterfour: '',
      paramefour: '',
      parameone: '',
      parametwo: '',
      paramethre: '',
      showcity: false,
      shopname: '',
      subtitle: '',
      stock: '',
      shoparea: '',
      shopent: '',
      shophone: '',
      shopcity: '',
      items: [],
      typext: '',
      activeId: [1, 2, 3, 4, 5, 6, 7],
      activeIndex: 0,
      shoplogo: '',
      shoptext: '',
      CardBefore: '',
      CardAfter: '',
      province: '',
      city: '',
      shopId: '',
      editid: this.$route.params.id,
      shenid: '',
    };
  },
  created() {
    authInfo().then((res) => {
      this.shenid = res.data.data.positionId;
    });
    this.init();
    qustores({ userId: this.userId }).then((res) => {
      this.shopId = res.data.data.id;
    });
    classifica().then((res) => {
      let label = res.data.data;
      label.forEach((element) => {
        this.types.push({ label: element.label, value: element.value });
      });
    });
  },
  methods: {
    drw() {
      this.drwpan = false;
      this.shoplogo = '';
    },
    figu() {
      this.figua = false;
      this.CardAfter = '';
    },
    itemck(data) {
      console.log(data.text, 444);
    },

    // 状态选择
    init() {
      if (this.editid != 0) {
        goodsDetail({ id: this.editid }).then((res) => {
          let info = res.data.data.info;
          let specificationList = res.data.data.specificationList;
          this.drawing = res.data.data.info.gallery;
          let pice = res.data.data.productList;
          let svtype = info.categoryIdCustomer;
          let ku;
          let cun;
          if (this.shoplogo == '') {
            this.shoplogo = res.data.data.info.gallery[0];
          }
          if (this.CardAfter == '') {
            if (specificationList.length > 0) {
              this.CardAfter = specificationList[0].valueList[0].picUrl;
            }
          }
          if (specificationList.length > 0) {
            this.figures = specificationList[0].valueList[0].picUrl;
          }

          pice.forEach((e) => {
            if (e.specifications[0] == '定金') {
              this.shopent = e.price;
              ku = e.number;
            } else if (e.specifications[0] == '全款') {
              this.shophone = e.price;
              cun = e.number;
            }
            if (ku < cun) {
              this.stock = cun;
            } else {
              this.stock = ku;
            }
            console.log(e);
          });
          this.shopname = info.name;
          this.subtitle = info.brief;

          console.log(res.data.data.info, 55);
        });
        // Toast(this.editid);
      }
    },

    selectWkType(option) {
      if (this.wkTypeSelected.length >= 3) {
        // 修改选择数量
        Toast('最多只能选择3个');
        return false;
      } else {
        return true;
      }
      return true;
    },

    // 提交
    upcard() {
      this.wkType = [];
      this.wkTypeSelected.forEach((L) => {
        this.wkType.push(L.value);
      });
      if (this.shopname == '') {
        Toast('请输入产品主题');
        return;
      }
      // if (this.subtitle == '') {
      //   Toast('请输入产品副标题');
      //   return;
      // }
      if (this.shopent == '') {
        Toast('请输入产品定金');
        return;
      }
      if (this.shophone == '') {
        Toast('请输入产品全款');
        return;
      }
      if (this.stock == '') {
        Toast('请输入产品库存');
        return;
      }
      if (this.shoplogo == '') {
        Toast('请上传产品主图');
        return;
      }
      if (this.shoptext == '') {
        Toast('请上传产品参数');
        return;
      }
      // if (this.wkTypeSelected.length == 0) {
      //   Toast('请选择服务类型');
      //   return;
      // }

      let zuihao = this.shoplogo;
      if (this.editid != 0) {
        // 修改
        if (this.shenid == 6001 || this.shenid == 2001 || this.shenid == 6004) {
          upsholiand({
            id: this.editid,
            detail: this.custom + this.shoptext,
            name: this.shopname,
            brief: this.subtitle,
            userId: this.userId,
            shopId: this.shopId,
            depositPrice: this.shopent,
            fullpayment: this.shophone,
            gallery: [zuihao],
            imager: this.CardAfter,
            number: this.stock,
            categoryId: this.wkType,
            info: `${this.parameterone}:${this.parameone},${this.parametertwo}:${this.parametwo},${this.parameterthre}:${this.paramethre},${this.parameterfour}:${this.paramefour}`,
          })
            .then((res) => {
              Toast('提交成功，请等待审核！');
              this.$router.go(-1);
              console.log(res.data, 5);
            })
            .catch((err) => {
              Toast(err.data.errmsg);
            });
        } else {
          // 免费
          upshod({
            id: this.editid,
            detail: this.custom + this.shoptext,
            name: this.shopname,
            brief: this.subtitle,
            userId: this.userId,
            shopId: this.shopId,
            depositPrice: this.shopent,
            fullpayment: this.shophone,
            gallery: [zuihao],
            imager: this.CardAfter,
            number: this.stock,
            categoryId: this.wkType,
            info: `${this.parameterone}:${this.parameone},${this.parametertwo}:${this.parametwo},${this.parameterthre}:${this.paramethre},${this.parameterfour}:${this.paramefour}`,
          })
            .then((res) => {
              Toast('提交成功，请等待审核！');
              this.$router.go(-1);
              console.log(res.data, 5);
            })
            .catch((err) => {
              Toast(err.data.errmsg);
            });
        }
      } else {
        // 添加
        if (this.shenid == 6001 || this.shenid == 2001 || this.shenid == 6004) {
          // 联盟
          addlianmen({
            detail: this.custom + this.shoptext,
            name: this.shopname,
            brief: this.subtitle,
            userId: this.userId,
            shopId: this.shopId,
            depositPrice: this.shopent,
            fullpayment: this.shophone,
            gallery: [zuihao],
            imager: this.CardAfter,
            number: this.stock,
            categoryId: this.wkType,
            info: `${this.parameterone}:${this.parameone},${this.parametertwo}:${this.parametwo},${this.parameterthre}:${this.paramethre},${this.parameterfour}:${this.paramefour}`,
          })
            .then((res) => {
              Toast('提交成功，请等待审核！');
              this.$router.go(-1);
              console.log(res.data, 5);
            })
            .catch((err) => {
              Toast(err.data.errmsg);
            });
        } else {
          // 免费
          adduct({
            detail: this.custom + this.shoptext,
            name: this.shopname,
            brief: this.subtitle,
            userId: this.userId,
            shopId: this.shopId,
            depositPrice: this.shopent,
            fullpayment: this.shophone,
            gallery: [zuihao],
            imager: this.CardAfter,
            number: this.stock,
            categoryId: this.wkType,
            info: `${this.parameterone}:${this.parameone},${this.parametertwo}:${this.parametwo},${this.parameterthre}:${this.paramethre},${this.parameterfour}:${this.paramefour}`,
          })
            .then((res) => {
              Toast('提交成功，请等待审核！');
              this.$router.go(-1);
              console.log(res.data, 5);
            })
            .catch((err) => {
              Toast(err.data.errmsg);
            });
        }
      }
    },
    getworkpe() {
      this.wkType = new Array();
      for (let i = 0; i < this.wkTypeSelected.length; i++) {
        if (this.setarr.get(this.wkTypeSelected[i])) {
          this.wkType.push(this.setarr.get(this.wkTypeSelected[i]));
        }
      }
    },

    // 图片上传
    uploadImg() {
      if (this.fileList.length > 1) return Toast('请上传2张以内的图片');
      this.show_upload = true;
      document.querySelector('.van-uploader__input').click();
      //   if (this.fileL.length > 1) return Toast('请上传2张以内的图片');
      //   this.show_upload = true;
      document.querySelector('.van-uploader__input').click();
    },
    beforeRead(file) {
      //上传之前校验
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        Toast('只允许上传jpg/png格式的图片！');
        return false;
      }
      if (file.size >= 5242880) {
        Toast('只允许上传小于5MB的图片！');
        return false;
      }
      return true;
    },
    async afterRead(file) {
      //文件读取完成后的回调函数
      file.status = 'uploading';
      file.message = '上传中...';
      let that = this;

      if (file.size < 1048576) {
        //图片小于1MB不压缩
        //成功时执行

        const formData = new FormData();
        formData.append('file', file.file);
        storageUpload(formData)
          .then((res) => {
            that.images.push(res.data.data.url);
            that.CardAfter = res.data.data.url;
            if (that.CardAfter != undefined) {
              file.status = '';
              file.message = '完成';
            }
          })
          .catch(() => {
            file.status = 'failed';
            file.message = '上传失败';
          });
      } else {
        lrz(file.file, {
          //width : 300
          quality: 0.7, //自定义使用压缩方式
        })
          .then(function (rst) {
            //成功时执行
            storageUpload(rst.formData)
              .then((res) => {
                that.images.push(res.data.data.url);
                that.CardAfter = res.data.data.url;
                if (that.CardAfter != undefined) {
                  file.status = '';
                  file.message = '完成';
                }
              })
              .catch(() => {
                file.status = 'failed';
                file.message = '上传失败';
              });
          })
          .catch(function (error) {
            //失败时执行
          })
          .always(function () {
            //不管成功或失败，都会执行
          });
      }
    },
    beforeDelete(file, detail) {
      this.images.splice(detail.index, 1);
      this.CardAfter = '';
      return true;
    },

    // 门头
    beforeR(file) {
      //上传之前校验
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        Toast('只允许上传jpg/png格式的图片！');
        return false;
      }
      if (file.size >= 5242880) {
        Toast('只允许上传小于5MB的图片！');
        return false;
      }
      return true;
    },
    async afterR(file) {
      //文件读取完成后的回调函数
      file.status = 'uploading';
      file.message = '上传中...';
      let that = this;

      if (file.size < 2048576) {
        //图片小于1MB不压缩
        //成功时执行
        const formData = new FormData();
        formData.append('file', file.file);
        storageUpload(formData)
          .then((res) => {
            that.images.push(res.data.data.url);
            that.shoplogo = res.data.data.url;
            if (that.shoplogo != undefined) {
              file.status = '';
              file.message = '完成';
            }
          })
          .catch(() => {
            file.status = 'failed';
            file.message = '上传失败';
          });
      } else {
        lrz(file.file, {
          //width : 300
          quality: 0.7, //自定义使用压缩方式
        })
          .then(function (rst) {
            //成功时执行

            storageUpload(rst.formData)
              .then((res) => {
                that.images.push(res.data.data.url);
                that.shoplogo = res.data.data.url;
                if (that.shoplogo != undefined) {
                  file.status = '';
                  file.message = '完成';
                }
              })
              .catch(() => {
                file.status = 'failed';
                file.message = '上传失败';
              });
          })
          .catch(function (error) {
            //失败时执行
            file.status = 'failed';
            file.message = '压缩失败';
          })
          .always(function () {
            //不管成功或失败，都会执行
          });
      }
    },
    beforeD(file, detail) {
      this.images.splice(detail.index, 1);
      this.shoplogo = '';
      return true;
    },
  },
  components: {
    [Checkbox.name]: Checkbox,
    [TreeSelect.name]: TreeSelect,
    [Field.name]: Field,
    [Uploader.name]: Uploader,
    [Toast.name]: Toast,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Area.name]: Area,
  },
};
</script>
<style lang="scss" scoped>
/deep/.vs__dropdown-toggle {
  border: none !important;
}
/deep/.van-field__label {
  width: auto !important;
}
.work_type {
  overflow: visible;
}

.work_type /deep/ .van-cell__value {
  overflow: visible;
}
</style>
